//! API客户端接口定义
//! 
//! 符合系统组件对接架构说明的接口定义

use crate::Result;
use crate::types::{Language, SandboxId, SandboxState};
use std::collections::HashMap;
use std::time::Duration;
use serde::{Serialize, Deserialize};
use async_trait::async_trait;

/// API执行结果（符合文档要求）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionResult {
    pub success: bool,
    pub stdout: String,
    pub stderr: String,
    pub exit_code: Option<i32>,
    pub execution_time_ms: u64,
    pub memory_usage_mb: u64,
}

/// 沙箱请求优先级
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum Priority {
    Low,
    Normal,
    High,
    Critical,
}

impl Default for Priority {
    fn default() -> Self {
        Self::Normal
    }
}

/// 资源需求配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceRequirements {
    pub memory_mb: u32,
    pub cpu_cores: u32,
    pub disk_mb: u32,
    pub network_enabled: bool,
}

impl Default for ResourceRequirements {
    fn default() -> Self {
        Self {
            memory_mb: 512,
            cpu_cores: 1,
            disk_mb: 1024,
            network_enabled: true,
        }
    }
}

/// 沙箱请求结构（符合文档要求）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxRequest {
    pub language: Language,
    pub version: String,
    pub resources: ResourceRequirements,
    pub timeout: Duration,
    pub priority: Priority,
}

/// 代码执行载荷（符合文档要求）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodePayload {
    pub source_code: String,
    pub language: Language,
    pub entry_point: Option<String>,
    pub dependencies: Vec<Dependency>,
    pub env_vars: HashMap<String, String>,
}

/// 依赖项定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dependency {
    pub name: String,
    pub version: String,
    pub source: Option<String>,
}

/// 沙箱信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxInfo {
    pub sandbox_id: SandboxId,
    pub language: Language,
    pub state: SandboxState,
    pub allocated_at: std::time::SystemTime,
    pub resources: ResourceRequirements,
}

/// 沙箱状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxStatus {
    pub sandbox_id: SandboxId,
    pub state: SandboxState,
    pub uptime: Option<Duration>,
    pub usage_count: usize,
    pub last_used_at: Option<std::time::SystemTime>,
    pub health: HealthStatus,
}

/// 健康状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum HealthStatus {
    Healthy,
    Degraded(String),
    Unhealthy(String),
}

/// 沙箱管理器客户端接口（符合文档2.1节要求）
#[async_trait]
pub trait SandboxManagerClient: Send + Sync {
    /// 请求分配沙箱
    async fn allocate_sandbox(&self, request: SandboxRequest) -> Result<SandboxInfo>;
    
    /// 执行代码
    async fn execute_code(&self, sandbox_id: String, code: CodePayload) -> Result<ExecutionResult>;
    
    /// 释放沙箱
    async fn release_sandbox(&self, sandbox_id: String) -> Result<()>;
    
    /// 获取沙箱状态
    async fn get_sandbox_status(&self, sandbox_id: String) -> Result<SandboxStatus>;
}

/// 测试作业消息（符合文档2.2节要求）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestJobMessage {
    pub job_id: String,
    pub project_id: String,
    pub sandbox_id: String,
    pub code: CodePayload,
    pub test_config: TestConfiguration,
    pub callback_url: Option<String>,
}

/// 测试配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestConfiguration {
    pub dimensions: Vec<TestDimension>,
    pub timeout: u64,
    pub test_cases: Vec<TestCase>,
    pub performance_targets: Option<PerformanceTargets>,
    pub security_checks: Option<SecurityChecks>,
}

/// 测试维度
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestDimension {
    pub name: String,
    pub weight: f64,
    pub enabled: bool,
}

/// 测试用例
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestCase {
    pub id: String,
    pub name: String,
    pub input: String,
    pub expected_output: String,
    pub timeout_ms: u64,
}

/// 性能目标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceTargets {
    pub max_latency_ms: u64,
    pub max_memory_mb: u64,
    pub max_cpu_percent: f64,
}

/// 安全检查配置
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityChecks {
    pub enable_static_analysis: bool,
    pub enable_runtime_monitoring: bool,
    pub blocked_syscalls: Vec<String>,
    pub network_restrictions: NetworkRestrictions,
}

/// 网络限制
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkRestrictions {
    pub allow_outbound: bool,
    pub allowed_domains: Vec<String>,
    pub blocked_ports: Vec<u16>,
}

/// 测试结果（符合文档要求）
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestResult {
    pub job_id: String,
    pub status: TestStatus,
    pub dimensions: HashMap<String, DimensionResult>,
    pub overall_score: f64,
    pub execution_time_ms: u64,
    pub issues: Vec<Issue>,
    pub recommendations: Vec<String>,
}

/// 测试状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TestStatus {
    Pending,
    Running,
    Completed,
    Failed(String),
    Cancelled,
}

/// 维度结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DimensionResult {
    pub name: String,
    pub score: f64,
    pub details: String,
    pub passed: bool,
}

/// 问题报告
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Issue {
    pub severity: IssueSeverity,
    pub category: String,
    pub message: String,
    pub location: Option<String>,
    pub suggestion: Option<String>,
}

/// 问题严重程度
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IssueSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

/// 服务错误定义（符合文档4.3节要求）
#[derive(Debug, thiserror::Error)]
pub enum ServiceError {
    #[error("Sandbox unavailable: {reason}")]
    SandboxUnavailable { reason: String },
    
    #[error("Test timeout for job {job_id} after {duration:?}")]
    TestTimeout { job_id: String, duration: Duration },
    
    #[error("Resource exhausted: {resource_type}")]
    ResourceExhausted { resource_type: String },
    
    #[error("Network error")]
    NetworkError { 
        #[source]
        source: Box<dyn std::error::Error + Send + Sync> 
    },
    
    #[error("Validation error in field {field}: {message}")]
    ValidationError { field: String, message: String },
}

/// 重试策略（符合文档4.3节要求）
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    pub max_attempts: u32,
    pub backoff: BackoffStrategy,
    pub retryable_errors: Vec<String>,
}

/// 退避策略
#[derive(Debug, Clone)]
pub enum BackoffStrategy {
    Fixed(Duration),
    Exponential { base: Duration, max: Duration },
    Jitter { min: Duration, max: Duration },
}

/// 连接池配置（符合文档4.1节要求）
#[derive(Debug, Clone)]
pub struct ConnectionPoolConfig {
    /// 沙箱管理器连接池
    pub sandbox_pool: PoolConfig,
    /// 数据库连接池
    pub db_pool: PoolConfig,
    /// Redis连接池
    pub redis_pool: PoolConfig,
}

/// 连接池配置详情
#[derive(Debug, Clone)]
pub struct PoolConfig {
    pub min_idle: usize,
    pub max_size: usize,
    pub connection_timeout: Duration,
    pub idle_timeout: Duration,
}

impl Default for ConnectionPoolConfig {
    fn default() -> Self {
        Self {
            sandbox_pool: PoolConfig {
                min_idle: 10,
                max_size: 100,
                connection_timeout: Duration::from_secs(5),
                idle_timeout: Duration::from_secs(300),
            },
            db_pool: PoolConfig {
                min_idle: 5,
                max_size: 50,
                connection_timeout: Duration::from_secs(3),
                idle_timeout: Duration::from_secs(600),
            },
            redis_pool: PoolConfig {
                min_idle: 5,
                max_size: 30,
                connection_timeout: Duration::from_secs(2),
                idle_timeout: Duration::from_secs(300),
            },
        }
    }
}